package lumis.util.converter;

import java.util.Locale;

/**
 * This converter is able to do conversion between {@link Boolean}, {@link Number}
 * and {@link String}. A number value is considered false only if it is equals
 * to zero. 
 * 
 * @version $Revision: 6251 $ $Date: 2007-03-27 10:49:29 -0300 (Tue, 27 Mar 2007) $
 * @since 4.0.4
 */
public class BooleanConverter extends AbstractConverter
{
	@SuppressWarnings("unchecked")
	@Override
	protected <T> T doConversion(Class<T> type, Object value, Locale locale,
			String pattern) throws UnsupportedConversionTypeException
	{
		// convert the value to a boolean value
		Boolean booleanValue;
		if (value instanceof Number)
			booleanValue = new Boolean(((Number)value).intValue() != 0);
		else if (value instanceof Boolean)
			booleanValue = ((Boolean)value);
		else
		{
			booleanValue = new Boolean(value.toString());
		}
		
		// convert booleanValue to the requested type
		if (Boolean.class.equals(type))
			return (T)booleanValue;
		else if (type.isAssignableFrom(String.class))
			return (T)booleanValue.toString();
		else if (Number.class.isAssignableFrom(type))
		{
			int intValue = booleanValue.booleanValue() ? 1 : 0;
			if (Integer.class.equals(type))
				return (T)new Integer(intValue);
			else if (Short.class.equals(type))
				return (T)new Short((short)intValue);
			else if (Double.class.equals(type))
				return (T)new Double(intValue);
			else if (Float.class.equals(type))
				return (T)new Float(intValue);
			else if (Long.class.equals(type))
				return (T)new Long(intValue);
			else if (Byte.class.equals(type))
				return (T)new Byte((byte)intValue);
			else if (Number.class.equals(type))
				return (T)new Integer(intValue);
		}
		throw new UnsupportedConversionTypeException(type.getName());
	}
}
